import '../../assets/js/libs/jquery.ztree.all.min.js'
import '../../assets/js/tableTree.js'
import {deepCopyObj} from '../../assets/js/help.js'

export default {
  props: {
    position: {
      type: String,
      default: 'table'
    },
    isNeedTree: [String, Boolean],
    isCheckbox: {
      type: Boolean,
      default: false
    },
    paramName: {
      type: String,
      default: 'parkId'
    },
    treeData: Array
  },
  data() {
    return {
      treeObj: null,
      treeInSearch: this.position === 'search',
      searchNode: {
        name: '',
        id: ''
      },
      searchVal: '',
      selectedNodeList: [],
      ztreeData:null
    }
  },
  created() {
    
  },
  mounted(){
    if (this.treeData) {
      this.bindTableTree(this.treeData);
    } else {
      this.getTreeData();
    }
  },
  methods: {
    getTreeData() {
      let self = this;
      API.GetTableTreeData()
        .then(res => {
          this.bindTableTree(res.data);
          this.treeObj = Object.freeze($.fn.zTree.getZTreeObj("tableTree"));
        }, err => {
          this.showToast('停车场树获取失败！', 2);
        })
    },
    // 绑定停车场的表格左侧的树
    bindTableTree(data, options) {
      let _data = JSON.stringify(data);
      _data = _data.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true,"nocheck":true,');
      _data = JSON.parse(_data);
      let userLoginId = window.sessionStorage.getItem('loginid')
      let curPagePath = this.$route.path
      let curPageCache = window.localStorage.getItem(userLoginId+'-'+curPagePath)
      let _curPageCache = curPageCache ? JSON.parse(curPageCache) : {}
      options = $.extend({}, options, {
        zNodes: _data,
        curPageCache: _curPageCache
      });
      this.ztreeData = deepCopyObj(options);
      $('#treeWrapper').bindAkeTree(options, this);
    },
    inputSearchVal() {
      if (this.searchVal == '') {
        this.searchNodes();
      }
    },
    searchNodes() {
      let self = this,
        Val = this.searchVal;
      this.updateNodes(false);
      if (Val) {
        this.selectedNodeList = this.treeObj.getNodesByParamFuzzy('name', Val);
        this.updateNodes(true);
        if (this.selectedNodeList.length == 0) {
          this.showToast('没有搜索到相匹配的数据！', 2, 1000, function () {
            self.searchVal = '';
          })
        } else {
          self.showToast('搜索成功', 1);
        }
      }
    },
    updateNodes(highlight) {
      let zTree = this.treeObj,
        nodeList = this.selectedNodeList;
      for (var i = 0, l = nodeList.length; i < l; i++) {
        if (highlight && nodeList[i].getParentNode()) {
          zTree.expandNode(nodeList[i].getParentNode(), true, false, true);
        }
        nodeList[i].highlight = highlight;
        zTree.updateNode(nodeList[i]);
      }
    },
    JudgeHasCheckedNode(treeId, treeNode, clickFlag){
			let treeObj = $.fn.zTree.getZTreeObj(treeId);
			let treeNodes = treeObj.getCheckedNodes(true)
			let nodes = treeNodes.filter(item=>item.isArea==false && item.childrenNum==0 && item.parkId)
			if(treeNode.value==='0'){ //全国
				if(!nodes.length){
					this.showToast('请先选择一类停车场',0,2000);
					return false
				}
				return true
			}
			return true
    },
    OnClickNode(event, treeId, treeNode) {
      if(treeNode.chkDisabled){
        return;
      }
      let isChecked = treeNode.checked;
      let treeObj = $.fn.zTree.getZTreeObj("tableTree");
      treeObj.checkNode(treeNode, !isChecked, false);
      this.OnCheckNode(event, treeId, treeNode)
    },
    OnCheckNode(event, treeId, treeNode) {
      let parkSysType = treeNode.parkSysType; //停车场类型
      let isChecked = treeNode.checked; //节点是否被选中
      let treeObj = $.fn.zTree.getZTreeObj("tableTree");
      if (this.isCheckbox) {
        let allNodesObj = treeObj.getNodes();
        let allNodes = allNodesObj[0].children; //获取全部子节点
				let treeNodes = treeObj.getCheckedNodes(true); //被选择的节点
				let nodes = treeNodes.filter(item=>item.isArea==false && item.childrenNum==0 && item.parkId)
				let selectedNodeLength = nodes.length
				if(!selectedNodeLength){
					allNodesObj[0].checked = false
					treeObj.checkNode(allNodesObj[0], false, false);
				}
				if(treeNode.value==='0'){ //全国
					if(isChecked){ //被选中
						let parkSysType = nodes[0].parkSysType //停车场类型
						allNodes.forEach(elem=>{
							if(elem.parkSysType==parkSysType){
								elem.checked = true
								treeObj.checkNode(elem, true, false);
								treeObj.setChkDisabled(elem, false);
							}else{
								elem.checked = false
								treeObj.checkNode(elem, false, false);
								treeObj.setChkDisabled(elem, true);
							}
						})
						return
					}else{ //取消选中状态
						allNodes.forEach(elem=>{
							elem.checked = false
							treeObj.checkNode(elem, false, false);
							treeObj.setChkDisabled(elem, false);
						})
						return
					}
				}
        for(let i = 0; i<allNodes.length; i++){
          if(allNodes[i].parkSysType!=parkSysType){
            if(!isChecked && !selectedNodeLength){ //取消选择
              treeObj.setChkDisabled(allNodes[i], false);
            }else{
              treeObj.setChkDisabled(allNodes[i], true);
            }
          }else{
            treeObj.setChkDisabled(allNodes[i], false);
          }
        }
      }
    },
    toggleTreeBox() {
      this.$emit('toggleTreeBox', 'hide');
    },
    splitWord(str) {
      if (str.indexOf("(") != -1) {
        var strs = str.split("(", 2);
        return strs[0];
      } else {
        return str;
      }
    },
    // 去除标签获取内容
    matchReg(str){
      let reg=/<\/?.+?\/?>/g;
      return str.replace(reg,'')
    },
    setSelectedNode(name, parkId, parkSysType) {
      let txt = this.matchReg(name),
        searchObj = {};
      this.searchNode.name = txt;
      this.searchNode.id = parkId;
      searchObj['parkIds'] = parkId;
      searchObj['name'] = txt;
      searchObj['parkSysType'] = parkSysType
      searchObj['parkIdParamName'] = this.paramName
      this.$emit('setSelectedNode', searchObj);
    }
  }
}
